#!/usr/bin/python

import os, ConfigParser
from optparse import OptionParser
from lib.core.common import check_file, create_directory
from lib.core.email import validate_email

VERSION = "0.3"
VERSION_STRING = "analyze/%s" % VERSION

# For testing
# CONFIG_FILE = "../../default.cfg"

def import_config(config_file):
	check_file(config_file)
	
	cfgparse = ConfigParser.RawConfigParser()
	cfgparse.read(config_file)
	
	# Check mandatory options
	if not cfgparse.has_section("Config"):
		raise NoSectionError, "config section in the configuration file is mandatory"
	
	if not cfgparse.has_option("Config", "ROOT_DIRECTORY"):
		raise NoOptionError, "ROOT_DIRECTORY option in the configuration file is mandatory"
		
	if not cfgparse.has_option("Config", "FROM_ADDR"):
		raise NoOptionError, "FROM_ADDR option in the configuration file is mandatory"
	
	validate_email(cfgparse.get("Config", "FROM_ADDR"))
	
	return cfgparse

def get_cmdline():
	usage = "%prog --ticket 123 --file malware.exe"
	
	optparse = OptionParser(usage=usage, version=VERSION_STRING)

	optparse.add_option("-t", "--ticket", type="int", dest="ticket", help="a ticket number to associate with the sample")
	optparse.add_option("-f", "--file", type="string", dest="filepath", help="the sample you want to analyze")

	(options, args) = optparse.parse_args()
	
	if not options.ticket:
		optparse.error("You must specify a valid ticket number")
	if not options.filepath:
		optparse.error("You must specify a valid file to analyze")

	check_file(options.filepath)

	return options

def merge_options(cfgparse, optparse):
	config = {}
	
	for section in cfgparse.sections():
		for option in cfgparse.options(section):
			config[option] = cfgparse.get(section, option)
	
	for key, value in optparse.__dict__.items():
		config[key] = value
	
	return config

def initialize(config_file):
	cfgparse = import_config(config_file)
	optparse = get_cmdline()
	
	return merge_options(cfgparse, optparse)
	
def print_config():
	for key, value in config.items():
		print "%s = %s" % (key, value)

if __name__ == "__main__":
	print "testing configuration file parser"
	
	initialize()
	
	print_config()
	